package com.yunchao.qrcode

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import by.kirich1409.viewbindingdelegate.viewBinding
import com.permissionx.guolindev.PermissionX
import com.xuexiang.xqrcode.XQRCode
import com.xuexiang.xui.utils.WidgetUtils
import com.yunchao.feature.base.presentation.activity.BaseActivity
import com.yunchao.feature.base.presentation.ext.setDebouncedClickListener
import com.yunchao.feature.base.presentation.ext.toast
import com.yunchao.qrcode.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class MainActivity : BaseActivity(R.layout.activity_main) {

    private val binding: ActivityMainBinding by viewBinding()
    private val invoiceInfoAdapter: InvoiceInfoAdapter by lazy { InvoiceInfoAdapter() }
    private val dir: File by lazy {
        getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            ?: filesDir.resolve(Environment.DIRECTORY_DOCUMENTS).also {
                it.mkdirs()
            }
    }

    @SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        XQRCode.setAutoFocusInterval(800)

        binding.recyclerView.apply {
            adapter = invoiceInfoAdapter
            WidgetUtils.initRecyclerView(this)
        }

        binding.button4.setDebouncedClickListener {
            XQRCode.startScan(this, REQUEST_CODE)
        }

        binding.button3.setDebouncedClickListener {

            val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10+ 不需要 WRITE_EXTERNAL_STORAGE，但可能需要 MANAGE_EXTERNAL_STORAGE
                if (Environment.isExternalStorageManager()) {
                    emptyList() // 已有权限
                } else {
                    listOf(android.Manifest.permission.MANAGE_EXTERNAL_STORAGE)
                }
            } else {
                // Android 9 及以下需要 WRITE_EXTERNAL_STORAGE
                listOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }

            PermissionX.init(this@MainActivity)
                .permissions(permissions)
                .onExplainRequestReason { scope, deniedList ->
                    // 解释为何需要权限
                    scope.showRequestReasonDialog(
                        deniedList,
                        "需要存储权限以保存发票文件",
                        "同意",
                        "拒绝"
                    )
                }
                .request { allGranted, _, _ ->
                    if (allGranted) {
                        // 权限已授予，执行文件保存逻辑
                        lifecycleScope.launch {
                            val result = saveToCustomDirectory(
                                this@MainActivity,
                                invoiceInfoAdapter.items
                            )
                            toast(message = if (result.isSuccess) "数据已保存到文件" else "保存失败")
                        }
                    } else {
                        toast("权限被拒绝，无法保存文件")
                    }
                }
        }

        binding.button2.setDebouncedClickListener {
            invoiceInfoAdapter.submitList(mutableListOf())
        }
    }


    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //处理二维码扫描结果
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            //处理扫描结果（在界面上显示）
            data?.extras?.run {
                takeIf { getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_SUCCESS }
                    ?.getString(XQRCode.RESULT_DATA)
                    ?.let(::processScanResult)
            }
        }
    }

    //处理扫描结果
    private fun processScanResult(result: String) {
        Log.i(TAG, "processScanResult: $result")
        // 实际的扫描结果处理逻辑
        InvoiceInfoModel.parseInvoice(result)?.let { data ->
            invoiceInfoAdapter.items.find { it.invoiceNumber == data.invoiceNumber }?.let {
                toast("已存在相同发票")
            } ?: invoiceInfoAdapter.add(data)

            lifecycleScope.launch {
                delay(1000)
                XQRCode.startScan(this@MainActivity, REQUEST_CODE)
            }
        }
    }

    @SuppressLint("QueryPermissionsNeeded")
    private fun openDirectory(context: Context, dir: File) {
        val uri = FileProvider.getUriForFile(
            context,
            "${context.packageName}.file provider",
            dir
        )

        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(uri, "resource/folder")
            flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
        }

        if (intent.resolveActivity(context.packageManager) != null) {
            context.startActivity(intent)
        } else {
            toast("没有可用的文件管理器")
        }
    }


    private suspend fun saveToCustomDirectory(context: Context, models: List<InvoiceInfoModel>) =
        withContext(Dispatchers.IO) {
            // Get current time for filename
            val dateFormat = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
            val currentTime = dateFormat.format(Date())
            val fileName = "发票-$currentTime.xlsx"

            // Define headers and data
            val headers = listOf(
                "固定标识",
                "发票种类代码",
                "发票代码",
                "发票号码",
                "开票金额",
                "开票日期",
                "发票校验码",
                "加密字符"
            )

            val data = listOf(headers) + models.map { model ->
                listOf(
                    model.fixedIdentifier,
                    model.invoiceTypeCode,
                    model.invoiceCode,
                    model.invoiceNumber,
                    model.amount,
                    model.date,
                    model.checkCode,
                    model.encryptionCode
                )
            }

            try {
                // Create Excel workbook
                XSSFWorkbook().use { workbook ->
                    // Create sheet
                    val sheet = workbook.createSheet("Sheet1")

                    // Write data to sheet
                    data.forEachIndexed { rowIndex, rowData ->
                        val row = sheet.createRow(rowIndex)
                        rowData.forEachIndexed { cellIndex, cellValue ->
                            val cell = row.createCell(cellIndex)
                            cell.setCellValue(cellValue?.toString() ?: "")
                        }
                    }

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        // Android 10+ - Use MediaStore
                        val resolver = context.contentResolver
                        val values = ContentValues().apply {
                            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
                            put(
                                MediaStore.MediaColumns.MIME_TYPE,
                                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                            )
                            put(
                                MediaStore.MediaColumns.RELATIVE_PATH,
                                Environment.DIRECTORY_DOCUMENTS + "/MyQRCodeApp"
                            )
                        }

                        val uri =
                            resolver.insert(MediaStore.Files.getContentUri("external"), values)
                        uri?.let {
                            resolver.openOutputStream(it)?.use { outputStream ->
                                workbook.write(outputStream)
                            }
                        } ?: throw IOException("Failed to create file URI")
                    } else {
                        // Android 9 and below - Direct file access
                        val dir = File(
                            Environment.getExternalStorageDirectory(),
                            Environment.DIRECTORY_DOCUMENTS + "/MyQRCodeApp"
                        )
                        if (!dir.exists()) dir.mkdirs()

                        val file = File(dir, fileName)
                        FileOutputStream(file).use { outputStream ->
                            workbook.write(outputStream)
                        }
                    }
                }
                Result.success(true)
            } catch (e: Exception) {
                e.printStackTrace()
                Result.failure(e)
            }
        }


    private suspend fun writeDataToExcel(models: List<InvoiceInfoModel>): Result<Boolean> =
        withContext(Dispatchers.IO) {
            // 定义表头
            val headers = listOf(
                "固定标识",
                "发票种类代码",
                "发票代码",
                "发票号码",
                "开票金额",
                "开票日期",
                "发票校验码",
                "加密字符"
            )
            val data = listOf(headers) + models.map { model ->
                listOf(
                    model.fixedIdentifier,
                    model.invoiceTypeCode,
                    model.invoiceCode,
                    model.invoiceNumber,
                    model.amount,
                    model.date,
                    model.checkCode,
                    model.encryptionCode
                )
            }

            // 获取当前时间
            val dateFormat = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
            val currentTime = dateFormat.format(Date())

            // 以当前时间命名文件
            val fileName = "发票-$currentTime.xlsx"
            // 保存文件
            val file = File(dir, fileName)

            try {
                XSSFWorkbook().use { workbook ->
                    // 创建工作表
                    val sheet = workbook.createSheet("Sheet1")

                    // 遍历数据并写入工作表
                    data.forEachIndexed { rowIndex, rowData ->
                        val row = sheet.createRow(rowIndex)
                        rowData.forEachIndexed { cellIndex, cellValue ->
                            val cell = row.createCell(cellIndex)
                            cell.setCellValue(cellValue)
                        }
                    }

                    FileOutputStream(file).use { fileOut ->
                        workbook.write(fileOut)
                    }
                }
                Result.success(true)
            } catch (e: IOException) {
                Result.failure(e)
            }
        }

    companion object {
        const val REQUEST_CODE = 111
        private const val TAG = "MainActivity"
    }
}